package com.itheima.stock.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName MyAspect
 * @Description TODO
 * @date 2023/2/25 19:02
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class MyAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("@annotation(com.itheima.stock.anno.MyAnno)")
    public void pt() {
    }

    @Around("pt()")
    public Object getCodeAround(ProceedingJoinPoint PJP) throws Throwable {

        System.out.println("增强前");
        Object[] args = PJP.getArgs();
        //获取当前ip
        HttpServletRequest request = (HttpServletRequest) args[0];
        String remoteHost = request.getRemoteHost();
        //拼接key
        String key = "api:captcha:ip:" + remoteHost + "";
//        查询

        String s = null;
        int i = 0;
        try {

            Boolean aBoolean = redisTemplate.hasKey(key);
            if (!aBoolean) {
                redisTemplate.opsForValue().set(key, 1 + "");
            } else {

                String s1 = redisTemplate.opsForValue().get(key);
                i = Integer.parseInt(s1) + 1;
                redisTemplate.opsForValue().set(key, String.valueOf(i));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        Object proceed = null;
        if (i <= 20) {
            proceed = PJP.proceed();

        }
        return proceed;
    }
}
